using System;
using MWTools.Client.Common;
using System.Reflection;
using MWTools.Client.Common.Interfaces;

namespace MWTools.Client.Plugins
{
    public class MediaWikiContentSubmitter : ContentSubmitterBase
    {
        public override void SubmitContent(string serverUri, string userName, string password, string title, string content)
        {
            WikiTools.Access.Wiki wiki = new WikiTools.Access.Wiki(serverUri);

            string modifiedContent = transformContent(content);

            wiki.Login(userName, password);
            wiki.CreatePage(title, modifiedContent, true);
            System.Diagnostics.Process.Start(string.Format(@"{0}/index.php?title={1}", serverUri, title));
        }

        private string transformContent(string xmlResult)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                string body = String.Empty;
                System.Xml.Xsl.XslTransform transform = new System.Xml.Xsl.XslTransform();

                //xslt document
                System.Xml.XmlDocument stylesheetDoc = new System.Xml.XmlDocument();
                string styleSheetPath = String.Format("{0}\\Resources\\OutlookItems.xslt", new System.IO.FileInfo(Assembly.GetExecutingAssembly().Location).Directory);


                try
                {
                    stylesheetDoc.Load(styleSheetPath);


                    //stylesheetDoc.Load(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MWTools.Client.Resources.OutlookItems.xslt"));
                    System.Xml.XPath.XPathNavigator stylesheetNav = stylesheetDoc.CreateNavigator();
                    transform.Load(stylesheetNav);
                }
                catch (System.Exception ex)
                {
                    Logger.DebugFormat("OutlookController.SubmitItemToWIki", "could not find path to xslt...", "");
                    throw;
                }

                System.Xml.XmlDocument inputDoc = new System.Xml.XmlDocument();
                inputDoc.LoadXml(xmlResult);
                inputDoc.Save(@"C:\scratch\dsout5.xml");

                System.Xml.XPath.XPathNavigator xmlNavigator = inputDoc.CreateNavigator();
                xmlNavigator.MoveToFirst();

                using (System.IO.MemoryStream resultStream = new System.IO.MemoryStream())
                {
                    transform.Transform(xmlNavigator, null, resultStream);
                    resultStream.Seek(0, System.IO.SeekOrigin.Begin);

                    using (System.IO.StreamReader sr = new System.IO.StreamReader(resultStream))
                    {
                        body = sr.ReadToEnd();
                    }

                }

                return body;

            }
        }
    }
}
